clear all;

load('withdraw_deposit.mat','withdraw','deposit','gridtheta','gridb','gridz','nmkt','nz','nb')
farmarketindex=2;
closemarketindex=1;

theta=0.8;
[~,thetaindex]=min(abs(gridtheta-theta));

%% far market
withdraw1=squeeze(withdraw(farmarketindex,:,:,thetaindex));
deposit1=squeeze(deposit(farmarketindex,:,:,thetaindex));

y1=gridz';
x1(1:nz,1)=nan;
y2=gridz';
x2(1:nz,1)=nan;
for i=1:nz
    index=find(withdraw1(i,:)==1,1,'first');
    if (~isempty(index))
        x1(i)=index;
    end

    index=find(deposit1(i,:)==1,1,'first');
    if (~isempty(index))
        x2(i)=index;
    end
end

cutoff=find(~isnan(x1)==1,1,'first');
x1=gridb(x1(cutoff:end));
y1=y1(cutoff:end);

cutoff=find(isnan(x2)==1,1,'first')-1;
x2=gridb(x2(1:cutoff));
y2=y2(1:cutoff);

figure;
plot(x1,y1);
hold on
plot(x2,y2);


%% close market
withdraw1=squeeze(withdraw(closemarketindex,:,:,thetaindex));
deposit1=squeeze(deposit(closemarketindex,:,:,thetaindex));

y3=gridz';
x3(1:nz,1)=nan;
y4=gridz';
x4(1:nz,1)=nan;
for i=1:nz
    index=find(withdraw1(i,:)==1,1,'first');
    if (~isempty(index))
        x3(i)=index;
    end

    index=find(deposit1(i,:)==1,1,'first');
    if (~isempty(index))
        x4(i)=index;
    end
end

cutoff=find(~isnan(x3)==1,1,'first');
x3=gridb(x3(cutoff:end));
y3=y3(cutoff:end);

cutoff=find(isnan(x4)==1,1,'first')-1;
x4=gridb(x4(1:cutoff));
y4=y4(1:cutoff);

figure;
plot(x3,y3);
hold on
plot(x4,y4);





figure('Color',[1,1,1],'position',[10,20,400,400])
withdraw1=squeeze(withdraw(1,:,:,thetaindex));
deposit1=squeeze(deposit(1,:,:,thetaindex));
[row,col]=find(withdraw1==1);
scatter(gridb(col),gridz(row),[],[1,0,0])
hold on
[row,col]=find(deposit1==1);
scatter(gridb(col),gridz(row),[],[0.5,0,0])

xlim([0,5])
ylim([1,2.5])


save('panelA.mat','x1','x2','x3','x4','y1','y2','y3','y4')